<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :labelWidth="110" :cols="3" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      columnsRef="partInventoryManagerPatrPriceAdjustIndex"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :pageSize="40"
      :onRowSelectChange="columns => (this.tableColumns = columns)"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="handleTableDataChange"
    >
      <!-- <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="updateHandle">批量修改</el-button>
      </template>-->
      <template slot="controls">
        <AjaxButton size="small" type="primary" :click="updateHandleNew">批量修改</AjaxButton>
        <el-button size="small" type="primary" :loading="totalUpdateBtnLoading" @click="updateTotalHandle">全量修改</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PartModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="updateStatus" :title="dialogTitle" destroyOnClose width="400px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PartUpdate :type="this.tableColumns" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getPartPriceAdjust, batchUpdatePrice, queryMainTableList, allUpdatePrice } from '@/api/part/inventoryManager/partPriceAdjust';
import PartModal from './partPriceEdit';
import PartUpdate from './partPriceUpdate';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { getStorageList, queryTex } from '@/api/part/common';
import moment from 'moment';
export default {
  name: 'Part',
  components: {
    PartModal,
    PartUpdate
  },
  mixins: [dictionary],
  data() {
    return {
      // topFilterList: this.createTopFilterList(),
      topFilterList: this.createTopFilterListNew(),
      fetchParams: { xhrAbort: true },
      visible: false,
      dialogTitle: '',
      tableColumns: [],
      // fetchApi: getPartPriceAdjust,
      fetchApi: queryMainTableList,
      // columns: this.createTableColumns(),
      columns: this.createTableColumnsNew(),
      handleType: '',
      formData: {},
      isShowWxll: false,
      updateStatus: false,
      showEdit: false,
      tableData: [], // table数据
      totalUpdateBtnLoading: false,
      tax: 0 // 税率
    };
  },
  computed: {
    compTax() {
      return this.tax || 0.13;
    }
  },
  mounted() {
    this.getStorage();
    this.queryTex();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          placeholder: '请选择...',
          request: {
            fetchApi: getStorageList,
            valueKey: 'STORAGE_CODE',
            textKey: 'STORAGE_NAME'
          }
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          placeholder: '配件代码...'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          placeholder: '配件名称...',
          showOverflowTooltip: true
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'PART_GROUP_CODE',
          placeholder: '请选择...',
          itemList: this.createDictList('8075')
        },
        {
          type: 'SELECT',
          label: '基准价类型',
          fieldName: 'BASE_COST_TYPE',
          placeholder: '请选择...',
          itemList: this.createDictList('8050'),
          initialValue: 80501002
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'RATE_END|RATE_BEGIN',
          placeholder: '请输入',
          precision: 2
          // rules: [{ pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '只允许输入非负数' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '价格系数大于',
        //   fieldName: 'RATE_BEGIN',
        //   placeholder: '价格系数大于...',
        //   rules: [{ pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '只允许输入非负数' }]
        // },
        {
          type: 'SELECT',
          label: '调整价类型',
          fieldName: 'IS_COST_TYPE',
          placeholder: '请选择...',
          itemList: [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ],
          initialValue: 80501002
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '最新进价',
          fieldName: 'PRICE_LOW|PRICE_HIGH',
          placeholder: '最新进价...'
        },
        {
          type: 'SELECT',
          label: '配件进销差价率',
          labelWidth: '130px',
          fieldName: 'partPriceLow',
          placeholder: '请选择...',
          itemList: [
            { value: 1, text: '等于' },
            { value: 2, text: '大于' },
            { value: 3, text: '小于' }
          ]
        },
        {
          type: 'INPUT_NUMBER',
          label: '',
          fieldName: 'partPriceNumber',
          placeholder: '配件进销差价率...',
          min: 0
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'REMARK',
          placeholder: '备注...'
        },
        {
          type: 'CHECKBOX',
          label: '现销售价＜成本价',
          labelWidth: '130px',
          fieldName: 'SALES_COST'
        },
        {
          type: 'CHECKBOX',
          label: '现销售价＜建议销售价',
          labelWidth: '130px',
          fieldName: 'SALES_ADVICE'
        },
        {
          type: 'CHECKBOX',
          label: '销售限价<销售价',
          labelWidth: '130px',
          fieldName: 'SALES_LIMIT'
        },
        {
          type: 'RANGE_DATE',
          dateType: 'daterange',
          label: '最近入库日期',
          fieldName: 'dateBegin|dateEnd',
          labelWidth: '100px',
          initialValue: [
            moment()
              .startOf('month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          ],
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'storageName',
          sorter: true,
          filter: true,
          filterType: 'input'
          // editItems: [],
          // editable: false
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件类别',
          dataIndex: 'partGroupCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('8075'),
          render: props => {
            return <span>{this.createDictText(props.row.partGroupCode, '8075')}</span>;
          }
        },
        {
          title: '配件代码',
          dataIndex: 'partNo2',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 140,
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 140,
          showOverflowTooltip: true
        },
        {
          title: '现含税销售价',
          dataIndex: 'salesPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '终端建议零售价格',
        //   dataIndex: 'insurancePrice',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '网点价',
        //   dataIndex: 'nodePrice',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '不含税采购价',
          dataIndex: 'latestPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '销售限价',
          dataIndex: 'limitPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税建议销售价',
          dataIndex: 'referPrice',
          // dataIndex: 'instructPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税成本价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        // {
        //   title: '索赔价',
        //   dataIndex: 'claimPrice',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '价格系数(%)',
          dataIndex: 'rate',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        }
      ];
    },
    createTopFilterListNew() {
      return [
        {
          type: 'INPUT',
          label: '主组号',
          fieldName: 'mainGroupNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '配件分类代码',
          fieldName: 'partSortCode',
          placeholder: '请选择...',
          itemList: this.createDictList(8106)
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'inOutTimeStr|inOutTimeEnd',
          labelOptions: {
            fieldName: 'inOutTime',
            itemList: [
              { text: '入库日期', value: 'inTime' },
              { text: '出库日期', value: 'outTime' },
              { text: '入出库日期', value: 'inOutTime' }
            ]
          }
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'priceType1',
          itemList: [
            { text: '不含税采购价', value: 'a.PLAN_PRICE' },
            { text: '含税销售价', value: 'a.COST_SALES_PRICE' },
            { text: '含税批发价', value: 'a.COST_WHOLESALES_PRICE' },
            // { text: '不含税参考零售价', value: 'c.REFER_PRICE' },
            { text: '含税参考零售价', value: `round(c.REFER_PRICE * ${1 + +(this.compTax || 0.13)}, 2)` }
          ]
        },
        {
          type: 'SELECT',
          fieldName: 'priceType2',
          itemList: [
            { text: '不含税采购价', value: 'a.PLAN_PRICE' },
            { text: '含税销售价', value: 'a.COST_SALES_PRICE' },
            { text: '含税批发价', value: 'a.COST_WHOLESALES_PRICE' },
            { text: '含税参考零售价', value: `round(c.REFER_PRICE * ${1 + +(this.compTax || 0.13)}, 2)` }
          ],
          labelOptions: {
            fieldName: 'sizeType',
            itemList: [
              { text: '等于', value: '=' },
              { text: '大于', value: '>' },
              { text: '小于', value: '<' },
              { text: '不等于', value: '<>' },
              { text: '大于等于', value: '>=' },
              { text: '小于等于', value: '<=' }
            ]
          }
        }
      ];
    },
    createTableColumnsNew() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '不含税采购价',
          dataIndex: 'planPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税销售单价',
          dataIndex: 'costSalesPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税批发单价',
          dataIndex: 'costWholesalesPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税参考零售价',
          dataIndex: 'referPrice',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税参考零售价',
          dataIndex: 'referPriceTaxed',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '储备高限',
          dataIndex: 'maxStock',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '储备低限',
          dataIndex: 'minStock',
          sorter: true,
          filter: true,
          filterType: 'number'
        }
      ];
    },
    async getStorage() {
      const res = await getStroageList();
      // const resdata = await findAllRepair();
      // this.topFilterList.find(x => x.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE + '' }));
      // this.topFilterList.find(x => x.fieldName === 'STORAGE_CODE').initialValue = resdata.data['1100'];
      // this.columns.find(x => x.dataIndex === 'storageCode').editItems = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE + '' }));
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    updateHandle() {
      if (this.tableColumns.length > 0) {
        this.showUpdate();
      } else {
        this.$notify.error({ title: '提示信息', message: '请选择要修改的记录!' });
      }
    },
    editHandle(row) {
      // console.log(row);
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    showHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    changeHandle(val) {
      console.log(val);
      // val.dateEnd = val.dateEnd ? val.dateEnd.split(' ')[0] + ' 23:59:59' : '';
      if (val.priceType1 && val.priceType2 && val.sizeType) {
        val.price = val.priceType1 + val.sizeType + val.priceType2;
      }
      if (val.inOutTime && val.inOutTimeStr && val.inOutTimeEnd) {
        val.inOutTimeEnd = val.inOutTimeEnd.split(' ')[0] + ' 23:59:59';
      } else {
        val.inOutTime = '';
        val.inOutTimeStr = '';
        val.inOutTimeEnd = '';
      }
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    // 点击批量修改
    async updateHandleNew() {
      if (this.tableColumns.length > 0) {
        let res = await batchUpdatePrice(this.tableColumns);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '修改成功' });
          this.fetchParams.xhrAbort = true;
          this.fetchParams.xhrAbort = false;
        }
      } else {
        this.$notify.warning({ title: '提示信息', message: '请选择要修改的记录!' });
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.dialogTitle = `配件价格修改`;
      this.visible = true;
    },
    showUpdate() {
      this.dialogTitle = `配件价格修改`;
      this.updateStatus = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      this.updateStatus = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 点击全量修改
    async updateTotalHandle() {
      let filterData = await this.$refs.topFilter.GET_FORM_DATA();
      let formData = filterData[1];

      // 过滤查询条件
      let { mainGroupNo, partNo, partSortCode, inOutTime, inOutTimeStr, inOutTimeEnd, priceType1, sizeType, priceType2 } = formData;
      let price = '';
      if (priceType1 && priceType2 && sizeType) {
        price = priceType1 + sizeType + priceType2;
      }
      if (inOutTime && inOutTimeStr && inOutTimeEnd) {
        inOutTimeEnd = inOutTimeEnd.split(' ')[0] + ' 23:59:59';
      } else {
        inOutTime = '';
        inOutTimeStr = '';
        inOutTimeEnd = '';
      }
      let postData = { mainGroupNo, partNo, partSortCode, inOutTime, inOutTimeStr, inOutTimeEnd, price };
      let filterFlag = false;
      for (let key in postData) {
        if (!!postData[key]) {
          filterFlag = true;
        }
      }
      if (!this.tableData.length && !filterFlag) {
        return this.$notify.warning({ title: '提示信息', message: '请先搜索数据!' });
      }
      if (this.totalUpdateBtnLoading) return;
      this.totalUpdateBtnLoading = true;
      try {
        let res = await allUpdatePrice(postData);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '批量修改成功' });
          this.fetchParams.xhrAbort = true;
          this.fetchParams.xhrAbort = false;
        }
      } catch (err) {
        console.log(err, '批量修改失败');
        this.totalUpdateBtnLoading = false;
      } finally {
        this.totalUpdateBtnLoading = false;
      }
    },
    // 查询税率
    async queryTex() {
      let res = await queryTex();
      this.tax = res.data || 0.13;
    },
    // 监听table数据变化
    async handleTableDataChange(val) {
      if (!this.tax) {
        let res = await queryTex();
        this.tax = res.data || 0.13;
      }
      val.map(item => {
        this.$set(item, 'referPriceTaxed', item.referPrice * (1 + +this.tax) || 0);
      });
      this.tableData = val;
    }
  }
};
</script>

<style lang="less" scoped></style>
